package com.dries.portal.module.chat.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dries.common.api.CommonResult;
import com.dries.portal.module.chat.entity.GroupChat;
import com.dries.portal.module.chat.entity.RecentChat;
import com.dries.portal.module.chat.enums.MsgAction;
import com.dries.portal.module.chat.service.IGroupChatService;
import com.dries.portal.module.chat.service.IRecentChatService;
import com.dries.portal.module.chat.vo.RecentChatVo;
import com.dries.portal.module.convener.entity.JoinConvener;
import com.dries.portal.module.convener.enums.JoinConvenerType;
import com.dries.portal.module.convener.service.IJoinConvenerService;
import com.dries.portal.module.user.entity.UserEntity;
import com.dries.portal.module.user.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author dries
 * @email samphsanie@gmail.com
 * @date 2020-09-14 14:03:33
 */
@RestController
@RequestMapping("/recentChat")
public class RecentChatController {

    @Resource
    private IGroupChatService groupChatService;
    @Resource
    private IRecentChatService recentChatService;
    @Resource
    private IJoinConvenerService joinConvenerService;
    @Resource
    private UserService userService;

    /**
     * 最近联系人列表
     */
    @GetMapping("/list/{userName}")
    public CommonResult list(@PathVariable String userName) {

        List<RecentChat> list = recentChatService.list(new QueryWrapper<RecentChat>().lambda()
                .eq(RecentChat::getType, MsgAction.CHAT_MSG.getCode())
                .eq(RecentChat::getSender, userName)
                .or()
                .eq(RecentChat::getAccept, userName)
        );

        List<String> senders = list.stream().map(RecentChat::getSender).collect(Collectors.toList());
        // List<String> accepts = list.stream().map(RecentChat::getAccept).collect(Collectors.toList());

        // List<String> usernames = Stream.of(senders, accepts).flatMap(Collection::stream).filter(e -> !e.equals(userName)).distinct().collect(Collectors.toList());

        if (CollUtil.isEmpty(senders)) {
            return CommonResult.success("暂无数据");
        }

        List<UserEntity> users = userService.list(new QueryWrapper<UserEntity>().lambda().in(UserEntity::getUsername, senders));
        List<RecentChatVo> RecentChats = users.stream().filter(e -> !e.getUsername().equals(userName))
                .map(e -> {
                    RecentChatVo recentChatVo = new RecentChatVo();
                    recentChatVo.setUserId(String.valueOf(e.getUserid()));
                    recentChatVo.setUsername(e.getUsername());
                    recentChatVo.setUserAvatar(e.getImghead());

                    list.forEach(l -> {
                        if (Objects.equals(l.getSender(), e.getUsername()) || Objects.equals(l.getAccept(), e.getUsername())) {
                            recentChatVo.setMsg(l.getMsg());
                            recentChatVo.setSignType(l.getMsgSign());
                            recentChatVo.setType(l.getType());
                            recentChatVo.setId(l.getId());
                        }
                    });

                    return recentChatVo;

                }).collect(Collectors.toList());

        return CommonResult.success(RecentChats);
    }

    /**
     * 最近群聊列表
     */
    @GetMapping("/group/list/{userName}")
    public CommonResult groupRecentChat(@PathVariable String userName) {

        List<GroupChat> chatList = groupChatService.list(new QueryWrapper<GroupChat>().lambda()
                .eq(GroupChat::getGroupUserName, userName)
        );

        List<RecentChat> list = recentChatService.list(new QueryWrapper<RecentChat>().lambda()
                .eq(RecentChat::getType, MsgAction.GROUP_CHAT_MSG.getCode())
                .eq(RecentChat::getSender, userName)
        );


        List<String> roomIds = list.stream().map(RecentChat::getAccept).collect(Collectors.toList());


        // 参与的召集令房间查询
        List<JoinConvener> conveners = joinConvenerService.list(new QueryWrapper<JoinConvener>().lambda()
                .eq(JoinConvener::getUserName, userName)
                .eq(JoinConvener::getStatus, JoinConvenerType.SIGNUP.getCode())
        );
        if (CollUtil.isNotEmpty(conveners)) {
            List<String> convenerIds = conveners.stream().map(item -> item.getConvenerId().toString()).collect(Collectors.toList());
            roomIds.addAll(convenerIds);
        }
        if (CollUtil.isEmpty(roomIds)) {
            return CommonResult.success(roomIds);
        }


        List<GroupChat> groupChats = groupChatService.listByIds(roomIds);

        // 合并群聊列表并去重
        List<GroupChat> collect = Stream.of(chatList, groupChats)
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());

        return CommonResult.success(collect);
    }


    /**
     * 信息
     */
    @GetMapping("/info/{id}")
    public CommonResult info(@PathVariable("id") Integer id) {
        RecentChat recentChat = recentChatService.getById(id);
        return CommonResult.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete")
    public CommonResult delete(@RequestBody Integer[] ids) {
        recentChatService.removeByIds(Arrays.asList(ids));
        return CommonResult.success();
    }

    /**
     * 删除
     */
    @DeleteMapping("/delete/{id}/{userName}")
    public CommonResult deleteGroup(@PathVariable String id,@PathVariable String userName) {
        // recentChatService.removeByIds(Arrays.asList(ids));
        recentChatService.remove(new QueryWrapper<RecentChat>().lambda()
                .eq(RecentChat::getSender, userName)
                .eq(RecentChat::getAccept, id)
        );
        return CommonResult.success();
    }

}
